<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import jyglService from '@/api/jygl'
import wjzs from '@/components/wjzs.vue'
import { ElMessage } from 'element-plus'
import printFn from '@/utils/print'
/*
 * 打开弹框
 */
const dialogVisible = ref<boolean>(false)
const loading = ref<boolean>(false)
const jysqbh = ref<string>('')
const url = ref<string>('')
// 入参
const wjzsRef = ref<InstanceType<typeof wjzs>>()
// 生命周期
const openDialog = (bh: string) => {
  jysqbh.value = bh
  dialogVisible.value = true
  loading.value = true
  const params = {
    jysqbh: bh,
  }
  jyglService.getJydwj(params).then((res) => {
    if (res.data.type === 'application/json') {
      const reader = new FileReader()
      reader.onload = () => {
        const jsonData =
          typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
        ElMessage({ type: 'warning', message: jsonData.message })
      }
      reader.readAsText(res.data)
    } else {
      url.value = window.URL.createObjectURL(res.data)
      nextTick(() => {
        wjzsRef.value?.init()
      })
    }
    loading.value = false
  })
}

// 下载按钮
const download = () => {
  window.location.href = `${window.IPCONFIG}/api/jygl/getJydwj?jysqbh=${jysqbh.value}`
}

const print = () => {
  const params = {
    fileSource: '2',
    localFilePathList: [],
    fileName: '借阅单.pdf',
    loadingHeader: {},
    loadingParam: {
      jysqbh: jysqbh.value,
    },
    loadingUrl: `${window.IPCONFIG}/api/jygl/getJydwj`,
    requestMethodName: 'GET',
  }
  printFn(params)
}
defineExpose({ openDialog })
</script>
<template>
  <el-dialog v-model="dialogVisible" title="借阅单" width="80%" :close-on-click-modal="false">
    <div class="dialog-box" v-loading="loading">
      <!--文件-->
      <wjzs ref="wjzsRef" wjlx="pdf" :url="url" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="download">下载</el-button>
        <el-button type="primary" @click="print">打印</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-box {
  width: 100%;
  height: 70vh;
}
</style>
